package com.edu.lwh.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.edu.lwh.pojo.JwtProperties;
import com.edu.lwh.pojo.LoginDto;
import com.edu.lwh.pojo.User;
import com.edu.lwh.service.UserService;
import com.edu.lwh.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("user")
public class LoginController {

    private static  final String USER_ID = "userId";
    @Resource
    private UserService userService;

    @Resource
    private JwtProperties jwtProperties;

    /**
     * 生成token
     * @param loginDto
     * @return
     */

    @PostMapping("/login")
    public String login(@RequestBody LoginDto loginDto){
//        非空校验
        if(ObjectUtil.hasEmpty(loginDto.getUsername(),loginDto.getPassword())){
            return "用户名或密码不能为null!";
        }
//      构造查询条件
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery()
                .eq(User::getUsername, loginDto.getUsername());
        User one = this.userService.getOne(wrapper);
        if(ObjectUtil.isEmpty(one)){
            return "没有该用户";
        }
//      比较密码
        if(ObjectUtil.notEqual(one.getPassword(),loginDto.getPassword())){
            return "密码错误";
        }

//      生成token 返回。
//        Map<String, Object> build = MapUtil.<String,Object>builder()
//                .put(USER_ID, one.getUid())
//                .build();
        String token = JwtUtil.createJWT(Convert.toStr(one.getUid()), loginDto.getUsername(), null);
        return token;
    }

    /**
     * 解析token。
     * @param token
     * @return
     * @throws Exception
     */
    @GetMapping("/parse")
    public Claims parseJwt(String token) throws Exception {
        Claims claims = JwtUtil.parseJWT(token);
        return claims;
    }
}
